package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    //远程注入UserService
    @Reference
    private UserService userService;

    //根据用户名查询用户信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用服务层
        User user = userService.findUserByUsername(username);

        if (user == null) {
            return null;
        }
        //创建集合,用于存储用户的角色和权限信息(核心对象)
        List<GrantedAuthority> list = new ArrayList<>();
        //根据user对象获取角色信息
        Set<Role> roles = user.getRoles();
        //遍历角色
        for (Role role : roles) {
            //通过角色表表里的角色关键字,给当前用户授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取该角色具有的权限
            Set<Permission> permissions = role.getPermissions();
            //遍历权限
            for (Permission permission : permissions) {
                //通过角色表表里的权限关键字,给当前用户授予权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //创建springSecurity安全框架所需的用户对象
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(username, user.getPassword(), list);
        return userDetails;
    }
}
